package net.aiotos.common.ice;

import lombok.extern.slf4j.Slf4j;
import net.aiotos.sdk.IOTOSysI;
import net.aiotos.common.dto.LoginResp;

import java.util.Date;

/**
 * 定时刷新Web Session, 解决授权失效问题
 * @author zws 2021.05.25
 */
@Slf4j
public class WebSessionRefreshThread extends Thread
{
    public volatile boolean exit = false;
    private final IOTOSysI iotoSysI;
    private final Integer serverTime = 25;
    private final long newTime = System.currentTimeMillis();

    public WebSessionRefreshThread(final IOTOSysI iotoSysI)
    {
        this.setName(this.getClass().toString());
        this.iotoSysI = iotoSysI;
    }

    @SuppressWarnings("static-access")
    public void run()
    {
        log.info("会话守护服务启动[{}]", getId());
        Date date = new Date();
        while (!exit)
        {
            try
            {
                this.sleep(60 * serverTime * 1000);
                date.setTime(System.currentTimeMillis());
                while (true) {
                    LoginResp loginResp = iotoSysI.loginWeb();
                    if(loginResp.getCode() == 0) {
                         break;
                    }
                    log.warn("刷新 web session 失败:{}, time:{}, ret:{}", (System.currentTimeMillis() - newTime) / 1000 / 60, date, loginResp);
                    sleep(5);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        log.warn("runTime:{}, time:{}", (System.currentTimeMillis() - newTime) / 1000 / 60, date);
    }

}
